package org.altervista.cp.microkernel.log;

import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;

import org.altervista.cp.microkernel.util.ClassLoaderUtils;

public class Log {

	static final java.util.logging.Logger _ROOT_LOGGER;

	static {
		URL loggingPropertiesURL = ClassLoaderUtils
				.lookupResource("logging.properties");
		try {
			if (loggingPropertiesURL == null) {
				LogManager.getLogManager().readConfiguration();
			} else {
				InputStream is = loggingPropertiesURL.openStream();
				LogManager.getLogManager().readConfiguration(is);
				is.close();
			}
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}

		_ROOT_LOGGER = java.util.logging.Logger.getLogger("MK_RootLogger");
		_ROOT_LOGGER.setUseParentHandlers(false);

	}

	public Log(Class<?> c) {
		this(c, null);
	}

	public Log(Class<?> c, Level debugLevel) {
		_logger = java.util.logging.Logger.getLogger(c.getName());
		_logger.setParent(_ROOT_LOGGER);
		_debugLevel = debugLevel == null ? Level.FINEST : debugLevel;
	}

	public void debug(String msg, Object... params) {
		_logger.log(getLogRecord(_debugLevel, msg, null, params));
	}

	public void debug(String msg, Throwable t, Object... params) {
		_logger.log(getLogRecord(_debugLevel, msg, t, params));
	}

	public void error(String msg, Object... params) {
		_logger.log(getLogRecord(Level.SEVERE, msg, null, params));
	}

	public void error(String msg, Throwable t, Object... params) {
		_logger.log(getLogRecord(Level.SEVERE, msg, t, params));
	}

	public void info(String msg, Object... params) {
		_logger.log(getLogRecord(Level.INFO, msg, null, params));
	}

	public void info(String msg, Throwable t, Object... params) {
		_logger.log(getLogRecord(Level.INFO, msg, t, params));
	}

	public void warn(String msg, Object... params) {
		_logger.log(getLogRecord(Level.WARNING, msg, null, params));
	}

	public void warn(String msg, Throwable t, Object... params) {
		_logger.log(getLogRecord(Level.WARNING, msg, t, params));
	}

	private LogRecord getLogRecord(Level level, String msg, Throwable t,
			Object... params) {
		LogRecord lr = new LogRecord(level, msg);
		lr.setMessage("[" + Thread.currentThread().getName() + "] - "
				+ lr.getMessage());
		lr.setSourceClassName(_logger.getName());
		if (t != null) {
			lr.setThrown(t);
		}
		if (params != null && params.length != 0) {
			lr.setParameters(params);
		}
		return lr;
	}

	private Level _debugLevel;
	private java.util.logging.Logger _logger;

}
